package edu.whu.tao.util;

import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaScriptUtil {

	private static ScriptEngineManager factory = new ScriptEngineManager();  
	private static ScriptEngine engine = factory.getEngineByName("JavaScript");
	
	public static final String DEFAULT_OLD_VALUE_KEY = "P";
	
	public static Double getMathValue(List<MapJ> list,String option){  
        double d = 0;  
        try {  
            for(int i=0; i < list.size();i++){  
            	MapJ mapJ = list.get(i);  
                option = option.replaceAll(mapJ.getKey(), mapJ.getValue());  
            }  
            Object o = engine.eval(option);  
            d = Double.parseDouble(o.toString());  
        } catch (ScriptException e) {  
            System.out.println("无法识别表达式");  
            return null;  
        }  
        return d;  
    }  
	
	public static Double getMathValue(String key,String value,String option){  
        double d = 0;  
        try {  
        	option = option.replaceAll(key, value);
            Object o = engine.eval(option);  
            d = Double.parseDouble(o.toString());  
        } catch (ScriptException e) {  
            System.out.println("无法识别表达式");  
            return null;  
        }  
        return d;  
    }  
	
	
	public static Double getMathValue(String value,String option){  
        
        return getMathValue(DEFAULT_OLD_VALUE_KEY,value,option);  
    }  
	
	
	
}
